﻿<%@ WebHandler Language="C#" Class="UploadImage" %>

using System;
using System.Web;

public class UploadImage : IHttpHandler {

    MyDbHelper mydb = new MyDbHelper();
    public void ProcessRequest(HttpContext context)
    {
        string sbr = "";
        ///context.Response.ContentType = "text/plain";
        context.Response.ContentType = "text/html";//这里一定要html
        
        //WriteLog(context, "访问上传图片接口");
        HttpPostedFile file = context.Request.Files["file"];
        string shopid =context.Request.Params["shopid"];
        string userid =context.Request.Params["userid"];
        string bdate = context.Request.Params["bdate"];
        if (file != null)
        {
            try
            {
                //图片保存的文件夹路径
                string path = context.Server.MapPath("~/photo/");
                //sbr = "{\"status\":\"" + path + "\",\"msg\":\"保存成功！\"}";
                //context.Response.Write(sbr);
                //context.Response.End();
                //每天上传的图片一个文件夹
                string folder = DateTime.Now.ToString("yyyyMMdd");
                //如果文件夹不存在，则创建
                if (!System.IO.Directory.Exists(path + folder))
                {
                    System.IO.Directory.CreateDirectory(path + folder);
                }
                //上传图片的扩展名
                string type = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                //保存图片的文件名
                string saveName = Guid.NewGuid().ToString() + type;
                //保存图片
                file.SaveAs(path + folder + "/" + saveName);

                sbr = "{\"status\":\"1\",\"msg\":\"" + shopid + "\"}";
                //插入图片数据。
                string sql = "insert into Bas_ShopReceiptImg values('" + shopid + "','" + bdate + "','" + userid + "',getdate(),'/photo/" + folder + "/" + saveName + "')";
                mydb.DM_ExecuteNonQuery(sql);
            }
            catch
            {
                sbr = "{\"status\":\"0\",\"msg\":\"保存失败！\"}";
            }
            
        }
        else
        {
            sbr = "{\"status\":\"文件传送失败！\",\"msg\":\"" + shopid + "！\"}";
        }
        context.Response.Write(sbr);
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    //1.正写日志 最新日志放最后面
    public void WriteLog(HttpContext context, string msg)
    {
        string strFilePath = context.Server.MapPath("logs.txt");
        System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
        sw.WriteLine("'" + DateTime.Now.ToString() + "： " + msg);
        sw.Close();
        fs.Close();
    }
}